package com.hx.jeeadminbase.utils;

import com.hx.jeeadminbase.db.utils.Record;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xinmiao.xu
 * @Emial: louis_hsu@yeah.net
 * @CreateDate: 2015年5月21日 下午7:11:08
 * @Description:
 */
public class DBUtil {

	// 1、注册驱动oracle.jdbc.driver.OracleDriver
	static {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("数据库驱动加载失败！");
		}
	}

	// 2、建立一个连接
	public static Connection getConnection(String url, String username, String password) throws SQLException {
		return DriverManager.getConnection(url, username, password);
	}

	public static Connection getConnection(String url, String username, String password, int seconds) throws SQLException {
		DriverManager.setLoginTimeout(seconds);
		return DriverManager.getConnection(url, username, password);
	}

	// 5、关闭资源
	public static void free(ResultSet rs, Statement stmt, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (stmt != null)
					stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (conn != null)
						conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static List<Record> result2List(ResultSet rs) {
		List<Record> list = null;
		ResultSetMetaData mdrs = null;
		if (rs != null) {
			try {
				mdrs = (ResultSetMetaData) rs.getMetaData();
				int nColumns = mdrs.getColumnCount();
				list = new ArrayList<Record>();
				while (rs.next()) {
					Record dynvo = new Record();
					for (int nk = 0; nk < nColumns; nk++) {
						//String cloumntype = mdrs.getColumnClassName(nk + 1).toUpperCase();// 获取字段对应的数据库类型
						String keyname = mdrs.getColumnName(nk + 1);
						dynvo.put(keyname, rs.getString(nk + 1));
					}
					list.add(dynvo);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list;
	}

}
